// Copyright 2024 Vadim Kharitonovich
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package lbs

import (
	"context"
	"errors"
	"fmt"
	"net"

	"github.com/alitto/pond"
	"notabug.org/overflowingd/lbs/pkg/log"
	"notabug.org/overflowingd/lbs/pkg/protocol/packet"
	"notabug.org/overflowingd/lbs/pkg/server"
)

type udpserver struct {
	options *server.Options
	handler server.Handler
}

func NewServer(handler server.Handler, opts ...server.Opt) server.Server {
	var u = udpserver{
		options: &server.Options{
			Workers: &server.WorkerPool{
				Min: 5,
				Max: 10,
			},
		},
		handler: handler,
	}

	for i := range opts {
		opts[i](u.options)
	}

	return &u
}

func (r *udpserver) HandleRequest(ctx context.Context, data []byte) ([]byte, error) {
	header, err := packet.ParseRequestHeader(data)
	if err != nil {
		return nil, fmt.Errorf("packet: parse request: %w", err)
	}

	var response *packet.Response

	switch header.Code {
	case packet.RequestNext:
		response = r.handler.Next(ctx, header)
	case packet.RequestRetain:
		payload := packet.UnserializeRetentionRequestPayload(data)
		if payload == nil {
			r.options.Logger.Debug("packet retention request payload malformed", log.Bytes("payload", data))
			return packet.ResponseUnsupportedSerialized, nil
		}

		r.handler.Retain(ctx, packet.NewRetentionRequest(header, payload))
		return nil, nil
	default:
		r.options.Logger.Debug("header code unsupported", log.Type("code", header.Code))
		return packet.ResponseUnsupportedSerialized, nil
	}

	if response == nil {
		// for cases when client does not wait any response
		return nil, nil
	}

	return packet.SerializeResponse(response), nil
}

func (r *udpserver) Listen(ctx context.Context, addr string) error {
	listener, err := net.ListenPacket("udp", addr)
	if err != nil {
		return fmt.Errorf("net: listen packet: %w", err)
	}

	go func() {
		<-ctx.Done()
		listener.Close()
		r.options.Logger.Debug("listener close")
	}()

	var (
		buf     = make([]byte, packet.RequestSizeMax)
		workers = pond.New(r.options.Workers.Max, 0, pond.Context(ctx), pond.MinWorkers(r.options.Workers.Min))
	)

	for {
		if ctx.Err() != nil {
			return nil
		}

		n, client, err := listener.ReadFrom(buf)
		if err != nil {
			if errors.Is(err, net.ErrClosed) {
				r.options.Logger.Debug("listener read from", log.Err(err))
				break
			}

			continue
		}

		data := make([]byte, n)
		copy(data, buf[:n])

		workers.Submit(func() {
			response, err := r.HandleRequest(ctx, data)
			if err != nil {
				r.options.Logger.Error("handle request", log.Err(err))
				return
			}

			if response == nil {
				return
			}

			_, err = listener.WriteTo(response, client)
			if err != nil {
				r.options.Logger.Error("listener write to", log.Err(err))
				return
			}
		})
	}

	return nil
}
